# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(dplyr)
library(optparse)
library(magrittr)
library(tidyr)
library(tibble)

option_list <- list(
make_option("--i", default = "AllMet1.csv", type = "character", help = "raw metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
    set_colnames(c("arg", "value")) %>%
    column_to_rownames("arg")

coef <- configData["coef", "value"] %>%
as.numeric()

tlog <- read.csv(opt$i, header = T, stringsAsFactors = F, row.names = 1)

head(tlog)

ndt01 <- data.frame()

for (i in 1 : dim(tlog)[1]) {
    value <- as.numeric(tlog[i,])
    QL <- quantile(value, probs = 0.25, na.rm = T)
    QU <- quantile(value, probs = 0.75, na.rm = T)
    QU_QL <- QU - QL
    coef <- coef
    # QL;QU;QU_QL
    test01 <- value
    out_imp01 <- max(test01[which(test01 <= QU + coef * QU_QL)])
    test01[which(test01 > QU + coef * QU_QL)] <- out_imp01
    # test01[which(is.na(test01) | test01 == 0)] <- out_imp01
    dt01 <- as.data.frame(t(test01))
    ndt01 <- rbind(ndt01, dt01)
}
ndt01 <- t1 <- as.matrix(ndt01)
rownames(ndt01) = rownames(tlog)
colnames(ndt01) = colnames(tlog)

data <- ndt01 %>%
    as.data.frame() %>%
    rownames_to_column("Raw_Metabolite")

write.csv(data, "01_AllMet_Raw_Outlier.csv", row.names = F)



